package com.crcode.crm.utils;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * jdbc接口
 * 
 * @author xzq create time 2017/04/28
 */
public class DBUtil {
	/**
	 * 创建连接
	 * 
	 * @return
	 * @throws IOException
	 * @author xzq
	 */
	public static Connection getConnection() throws IOException {
		Connection conn = null;
		// 加载属性文件数据
		Properties prop = new Properties();
		prop.load(DBUtil.class.getClassLoader().getResourceAsStream("application.properties"));
		String driverclass = prop.getProperty("spring.datasource.driver-class-name");
		String url = prop.getProperty("spring.datasource.url");
		String user = prop.getProperty("spring.datasource.username");
		String password = prop.getProperty("spring.datasource.password");
		try {
			Class.forName(driverclass);
			conn = DriverManager.getConnection(url, user, password);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	/**
	 * 关闭连接
	 * 
	 * @param rs
	 * @param stmt
	 * @param conn
	 * @author xzq
	 */
	public static void close(ResultSet rs, Statement stmt, Connection conn) {

		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (stmt != null) {
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 归还连接
	 * 
	 * @param conn
	 * @author xzq
	 */
	public static void close(Connection conn) {
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();

			}
		}
	}

}

class testDBUtil {
	// 测试
	@SuppressWarnings("static-access")
	public static void main(String[] args) throws SQLException, IOException {
		DBUtil db = new DBUtil();
		Connection conn = db.getConnection();
		System.out.println(conn.getClass().getName());
		db.close(conn);
	}
}